const nodemailer = require('nodemailer')

const { Failed } = require('../../core/exception')

const redisCache = require('../../core/redis')

const config = require('../../config/config')

const transporter = nodemailer.createTransport({
    host: config.email.host,
    //service: config.email.service,
    port: config.email.port, // SMTP 端口
    secure: config.email.secure, // 使用了 SSL
    auth: {
        user: config.email.user,
        pass: config.email.pass,
    }
})

const sendEmail = async (name, email) => {
    // 生成六位随机验证码
    const code = Math.floor(Math.random()*(999999-100000+1)+100000)
    // 生成邮箱模板
    const html = 
    `
        <html>
            <head>
                <meta http-equiv="Content-Language" content="zh-cn">
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            </head>
            <body>
                尊敬的${ name }，您好！
                <br />
                <br />
                <br />
                欢迎您加入墨色坊，您的验证码为：
                <br />
                <br />
                <h1 style="color: #324157; text-indent: 2em;">${ code }</h1>
                <br />
                <br />
                本次验证码有效时间为 15 分钟，请尽快填写。如果您并未尝试激活邮箱，请忽略本邮件，由此给您带来的不便请谅解。<br />
                <br />
                <br />
                本邮件由系统自动发出，请勿直接回复！
            </body>
        </html>
    `
    // 发件配置
    const mailOptions = {
        from: `墨色坊<${config.email.user}>`,
        to: email,
        subject: '【墨色坊】验证码',
        html
    }
    const codeKey = `code_${email}`
    const queryRedis = await redisCache.getItem(codeKey)
    // console.log('queryRedis', queryRedis)
    if (queryRedis) {
        let obj = JSON.parse(queryRedis)
        if ((parseInt(Date.now()/1000) - parseInt(obj.dateTime/1000)) < 10) {
            throw new Failed({ errMsg: '120s内不可重复发送' })
        }
    }
    // 发送邮件
    return new Promise((resolve, reject)=>{
        transporter.sendMail(mailOptions, async (err, data) => {
            if (err) {
                reject(err)    //出错
            } else {
                // 设置 redis
                let obj = JSON.stringify({email, code, dateTime: Date.now()})
                const res = await redisCache.setItem(codeKey, obj, 60 * 15) // 15分钟过期
                resolve(res)    //成功
            }
        })
    })
}


module.exports = {
    sendEmail
}
